import { useMutation } from '@tanstack/react-query';
import { App, Button, Input, Select, Switch } from 'antd';
import React, { useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import MyModal from '@/components/MyModal';
import { t } from '@/locales/i18n';
import {
  FlowNodeInputTypeEnum,
  toolValueTypeList,
  WorkflowIOValueTypeEnum,
} from '@/types/workflow/constant';
import { FlowNodeInputItemType } from '@/types/workflow/io';

import { WorkflowContext } from '../../../../context';

import { EditFieldModalProps } from './type';

const { TextArea } = Input;

const EditFieldModal = ({
  defaultValue = defaultEditFormData,
  nodeId,
  onClose,
}: EditFieldModalProps) => {
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);
  const { message } = App.useApp();
  const [value, setValue] = useState<FlowNodeInputItemType>(defaultValue.value);

  const { mutate: onclickSubmit } = useMutation({
    mutationFn: async (e: FlowNodeInputItemType) => {
      e.key = e.key.trim();

      const inputConfig: FlowNodeInputItemType = {
        ...e,
        description: e.toolDescription,
        label: e.key,
      };
      if (defaultValue.key) {
        // edit
        onChangeNode({
          nodeId,
          type: 'replaceInput',
          key: defaultValue.key,
          value: inputConfig,
        });
      } else {
        // create
        onChangeNode({
          nodeId,
          type: 'addInput',
          index: 1,
          value: {
            ...e,
            label: e.key,
          },
        });
      }
      onClose();
    },
  });

  return (
    <MyModal isOpen iconSrc="modal/edit" title={t('tool_field')} onClose={onClose}>
      <div>
        <div className="mb-5 flex items-center gap-2">
          <span>{t('common.Require Input')}</span>
          <Switch
            value={value.required}
            onChange={(e) => {
              setValue((prev) => {
                return {
                  ...prev,
                  required: e,
                };
              });
            }}
          />
        </div>
        <div className="mb-5 flex items-center gap-2">
          <span>{t('core.module.Data Type')}</span>
          <div className="flex-1">
            <Select
              className="w-full"
              popupClassName="workflow-dropdown"
              options={toolValueTypeList}
              value={value.valueType}
              onChange={(e: any) => {
                setValue((prev) => {
                  return {
                    ...prev,
                    valueType: e,
                  };
                });
              }}
            />
          </div>
        </div>
        <div className="mb-5 flex items-center gap-2">
          <span>{t('core.module.Field Name')}</span>
          <Input
            className="bg-gray-500"
            value={value.key}
            onChange={(e) => {
              setValue((prev) => {
                return {
                  ...prev,
                  key: e.target.value,
                };
              });
            }}
          />
        </div>
        <div className="mb-5 gap-2">
          <span>{t('core.module.Field Description')}</span>
          <TextArea
            className="bg-gray-500"
            rows={5}
            value={value.toolDescription}
            onChange={(e) => {
              setValue((prev) => {
                return {
                  ...prev,
                  toolDescription: e.target.value,
                };
              });
            }}
          />
        </div>
      </div>
      <div className="ml-auto mt-4 flex gap-2">
        <Button onClick={onClose}>{t('common.Close')}</Button>
        <Button
          onClick={() => {
            onclickSubmit(value);
          }}
        >
          {t('common.Confirm')}
        </Button>
      </div>
    </MyModal>
  );
};

export default React.memo(EditFieldModal);

export const defaultEditFormData: FlowNodeInputItemType = {
  valueType: WorkflowIOValueTypeEnum.string,
  renderTypeList: [FlowNodeInputTypeEnum.reference],
  key: '',
  label: '',
  toolDescription: '',
  required: true,
  canEdit: true,
  customInputConfig: {
    selectValueTypeList: Object.values(toolValueTypeList).map((item) => item.value),
    showDescription: true,
  },
};
